package com.etone.smartAudit.commService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etone.smartAudit.domain.PLogVersion;
import com.etone.smartAudit.domain.PUumUserinfo;
import com.etone.smartAudit.dto.PageDTO;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.PUumUserinfoMapper;
import com.etone.smartAudit.vo.PUumOrgVO;
import com.etone.smartAudit.vo.PUumUserinfoVO;
import com.etone.smartAudit.vo.PagerVO;
import com.etone.smartAudit.vo.PortalBaseVo;
import com.etone.smartAudit.vo.workOrder.AuditManVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author jiayen
 * @since 2021-12-07 11:58:34
 */
@Slf4j
@Service
public class CommPUumUserinfoService extends ServiceImpl<PUumUserinfoMapper, PUumUserinfo> {


    @Autowired
    private CommPUumOrganizationinfoService organizationinfoService;


    /***
     * 添加进组织
     */
    public void addUsrInfo(PUumUserinfo userinfo) {
        //判断该组织是否已经存在， 存在则更新
        String employee = userinfo.getEmployee();
        LambdaQueryWrapper<PUumUserinfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PUumUserinfo::getEmployee, employee);
        PUumUserinfo exsitUser = this.getOne(queryWrapper);

        if (exsitUser != null) {
            //更新
            this.update(userinfo, queryWrapper);
        } else {
            //添加
            this.save(userinfo);
        }
    }

    /***
     * 搜索用户
     * @param pageDTO
     * @return
     */
    public PagerVO<PUumUserinfoVO> getUsersPage(PageDTO pageDTO) {
        Page<PUumUserinfoVO> page = PageHelper.startPage(pageDTO.getPage(), pageDTO.getPageSize())
                .doSelectPage(() -> baseMapper.getUsersPage(pageDTO));
        page.getResult().stream().forEach(vo -> {
            //处理数据结构  o
            //orgDN o=政企客户中心,o=阳春分公司,o=阳江分公司,dc=gmcc,dc=net
            String dn = vo.getOrgDN();
            if (StrUtil.isNotEmpty(dn)) {
                String[] strs = dn.split(",");
                List<String> dnList = new ArrayList<>();
                for (String d : strs) {
                    if (StrUtil.isNotEmpty(d)) {
                        String[] temps = d.split("=");
                        if (temps.length > 1) {
                            dnList.add(temps[1]);
                        }
                    }
                }
                Collections.reverse(dnList);
                StringJoiner sb = new StringJoiner("->");
                dnList.stream().forEach(t -> {
                            if (!"gmcc".equals(t) && !"net".equals(t)) {
                                sb.add(t);
                            }
                        }
                );
                vo.setOrgDN(sb.toString());
            }
        });
        return PagerVO.of(page);
    }


    /***
     * 搜索用户
     * @param pageDTO
     * @return
     */
    public PagerVO<PUumUserinfoVO> getCompanyUsers(PageDTO pageDTO) {
        String ouId = pageDTO.getOuguId();
        String companyId  = pageDTO.getCompanyId();
        if (StrUtil.isEmpty(ouId)&&StrUtil.isEmpty(companyId)) {
            throw new CustomParameterizedException("请选择公司");
        }
        if (StrUtil.isEmpty(companyId)) {
            pageDTO.setCompanyId(ouId);
        }
        Page<PUumUserinfoVO> page = PageHelper.startPage(pageDTO.getPage(), pageDTO.getPageSize())
                .doSelectPage(() -> baseMapper.getCompanyUser(pageDTO));
        return PagerVO.of(page);
    }

    /***
     * 同步到存证单关联人员表
     */
    public void copyPuumUserToCerPersonInfos() {
//        CertificatePersonInfo

        return;
    }

    /***
     * 获取组织树
     * @return
     */
    public List<PUumOrgVO> getUserOrg() {

        return organizationinfoService.getOrgTree();
    }

    public List<AuditManVO> companyAudit(String company) {
        return baseMapper.getCompanyAudit(company);
    }

    /***
     * 根据父级获取子级列表
     * @param parentId
     * @return
     */
    public List<PUumOrgVO> getOrgList(String parentId) {

        return organizationinfoService.getOrgList(parentId);
    }

    /***
     * 用户组织树
     * @param pageDTO
     * @return
     */
    public List<PUumOrgVO> usersTree(PageDTO pageDTO) {
        try {


            String ouId = pageDTO.getOuguId();
            if (StrUtil.isEmpty(ouId)) {
                throw new CustomParameterizedException("请选择一个上级公司");
            }

            List<PUumOrgVO> orgList = new ArrayList<>();
            if (StrUtil.isNotEmpty(ouId)) {
                //获取其下所有子集公司或者部门
                List<String> childIds = new ArrayList<>();
                childIds.add(ouId);
                getchildList(ouId, orgList);
                orgList.stream().forEach(org -> {
                    if (!childIds.contains(org.getOUGUID())) {
                        childIds.add(org.getOUGUID());
                    }
                });
                if (CollectionUtil.isNotEmpty(childIds)) {
                    pageDTO.setOuguIds(childIds);
                    pageDTO.setHasList(true);
                }

            }

            Page<PUumUserinfoVO> page = PageHelper.startPage(pageDTO.getPage(), pageDTO.getPageSize())
                    .doSelectPage(() -> baseMapper.getUsersPage(pageDTO));
            List<PUumUserinfoVO> list = page.getResult();
            if (CollectionUtil.isNotEmpty(list)) {
                //按部门分组用户
                Map<String, List<PUumUserinfoVO>> usersMap = new HashMap<>();
                list.stream().forEach(user -> {
                    String ougId = user.getOUGUID();
                    List<PUumUserinfoVO> uList = usersMap.get(ougId);
                    if (uList == null) {
                        uList = new ArrayList<>();
                        usersMap.put(ougId, uList);
                    }
                    if (!uList.contains(user)) {
                        uList.add(user);
                    }
                });

                //过滤没有用户的组织数据
                Map<String, PUumOrgVO> orgVOMap = new HashMap<>();
//              把用户放到组织下面
                List<PUumOrgVO> fistOrgs = new ArrayList<>();

                orgList.stream().forEach(org -> {
                    if (org != null) {
                        orgVOMap.put(org.getOUGUID(), org);
                        String ougId = org.getOUGUID();
                        List<PUumUserinfoVO> users = usersMap.get(ougId);
                        if (CollectionUtil.isNotEmpty(users)) {
                            org.setHasUser(true);
                            org.setUsers(users);
                        } else {
                            org.setHasUser(false);
                        }
                    }
                });

                orgList = filterUserOrg(list, orgVOMap);
                List<PUumOrgVO> rpeatOrg = new ArrayList<>();
                orgList.stream().forEach(org -> {
                    if (pageDTO.getOuguId().equals(org.getParentOUGUID())) {
                        if (!fistOrgs.contains(org)) {
                            fistOrgs.add(org);
                        }
                    }
                    //去重
                    if (!rpeatOrg.contains(org)) {
                        rpeatOrg.add(org);
                    }
                });
                //处理树形结构
                organizationinfoService.handorgTree(rpeatOrg, fistOrgs);

                return fistOrgs;
            }
        } catch (Exception e) {
            throw new CustomParameterizedException(e.getMessage());
        } finally {
            //清理内存
            System.gc();
        }
        return null;
    }

    /***
     * 过滤没与人员的公司
     * @param list
     * @param orgVOMap
     * @return
     */
    private List<PUumOrgVO> filterUserOrg(List<PUumUserinfoVO> list, Map<String, PUumOrgVO> orgVOMap) {
        List<PUumOrgVO> orgs = new ArrayList<>();
        //过滤没有用户的组织数据
        list.stream().forEach(user -> {
            String ouguId = user.getOUGUID();
            handFilterOrg(ouguId, orgVOMap, orgs);
        });
        return orgs;
    }

    private void handFilterOrg(String ouguId, Map<String, PUumOrgVO> orgVOMap, List<PUumOrgVO> orgs) {
        PUumOrgVO curVo = orgVOMap.get(ouguId);
        if (curVo != null) {
            orgs.add(curVo);
            handFilterOrg(curVo.getParentOUGUID(), orgVOMap, orgs);
        }
    }

    /**
     * 获取子集节点
     */
    private void getchildList(String ouId, List<PUumOrgVO> orgList) {

        List<PUumOrgVO> list = getOrgList(ouId);
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(org -> {
                if (org != null) {
                    String ougId = org.getOUGUID();
                    if (!orgList.contains(org)) {
                        orgList.add(org);
                        getchildList(ougId, orgList);
                    }
                }
            });
        }
    }


    /***
     * 搜索现有的数据变成树结构
     * @param orgMap
     * @param usersMap
     * @return
     */
    private List<PUumOrgVO> toTree(Map<String, PUumOrgVO> orgMap, Map<String, List<PUumUserinfoVO>> usersMap) {
        List<PUumOrgVO> orgs = new ArrayList<>();
        usersMap.forEach((ougId, users) -> {
            PUumOrgVO curOrg = orgMap.get(ougId);
            if (curOrg != null) {
                if (CollectionUtil.isNotEmpty(users)) {
                    curOrg.setHasUser(true);
                    curOrg.setUsers(users);
                }
                PUumOrgVO orgVO = handParentOrg(curOrg, orgMap);
                if (orgVO != null) {
                    orgs.add(orgVO);
                }
            }
        });
        return orgs;
    }

    /***
     * 处理父级
     * @param curOrg
     * @param orgMap
     */
    private PUumOrgVO handParentOrg(PUumOrgVO curOrg, Map<String, PUumOrgVO> orgMap) {
        String parentId = curOrg.getParentOUGUID();
        if (StrUtil.isNotEmpty(parentId)) {
            PUumOrgVO parentOrg = orgMap.get(parentId);
            if (parentOrg != null) {
                List<PUumOrgVO> childs = new ArrayList<>();
                childs.add(curOrg);
                parentOrg.setChildren(childs);
                return handParentOrg(parentOrg, orgMap);
            } else {
                return curOrg;
            }
        }
        return curOrg;
    }

    public List<PUumUserinfoVO> getDeptMan(String departmentID) {
        PageDTO pageDTO = new PageDTO();
        pageDTO.setOuguId(departmentID);
        return baseMapper.getUsersPage(pageDTO);
    }

    /***
     * 根据用户id获取用户详细信息
     * @param userId
     * @return
     */
    public PUumUserinfoVO getUserInfoByUserId(String userId) {
        LambdaQueryWrapper<PUumUserinfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PUumUserinfo::getUserID, userId);
        PUumUserinfo exsitUser = this.getOne(queryWrapper);
        PUumUserinfoVO vo = new PUumUserinfoVO();
        if (exsitUser != null) {
            BeanUtils.copyProperties(exsitUser, vo);
        }
        return vo;
    }
}
